package com.cyh.jsbridgex5;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.cyh.jsbridgex5.lib.BridgeHandler;
import com.cyh.jsbridgex5.lib.BridgeWebView;
import com.cyh.jsbridgex5.lib.CallBackFunction;
import com.cyh.jsbridgex5.lib.DefaultHandler;
import com.google.gson.Gson;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends Activity implements OnClickListener {

	private final String TAG = "MainActivity";

	BridgeWebView webView;

	Button button_1;
	Button button_2;
	Button button_3;

	int RESULT_CODE = 0;

	ValueCallback<Uri> mUploadMessage;

    static class Location {
        String address;
    }

    static class User {
        String name;
        Location location;
        String testStr;
    }

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		permission();

        webView = (BridgeWebView) findViewById(R.id.webView);

		button_1 = (Button) findViewById(R.id.button_1);
		button_2 = (Button) findViewById(R.id.button_2);
		button_3 = (Button) findViewById(R.id.button_3);

		button_1.setOnClickListener(this);
		button_2.setOnClickListener(this);
		button_3.setOnClickListener(this);

		webView.setDefaultHandler(new DefaultHandler() {
			@Override
			public void handler(String data, CallBackFunction function) {
				Log.i(TAG, "setDefaultHandler -- data = " + data);
				super.handler(data, function);
			}
		});

		webView.setWebChromeClient(new WebChromeClient() {

			@SuppressWarnings("unused")
			public void openFileChooser(ValueCallback<Uri> uploadMsg, String AcceptType, String capture) {
				this.openFileChooser(uploadMsg);
			}

			@SuppressWarnings("unused")
			public void openFileChooser(ValueCallback<Uri> uploadMsg, String AcceptType) {
				this.openFileChooser(uploadMsg);
			}

			public void openFileChooser(ValueCallback<Uri> uploadMsg) {
				mUploadMessage = uploadMsg;
				pickFile();
			}
		});

		webView.loadUrl("file:///android_asset/demo.html");

		webView.registerHandler("submitFromWeb", new BridgeHandler() {

			@Override
			public void handler(String data, CallBackFunction function) {
				Log.i(TAG, "handler = submitFromWeb, data from web = " + data);
                function.onCallBack("submitFromWeb exe, response data 中文 from Java");
			}

		});

	}

	public void pickFile() {
		Intent chooserIntent = new Intent(Intent.ACTION_GET_CONTENT);
		chooserIntent.setType("image/*");
		startActivityForResult(chooserIntent, RESULT_CODE);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (requestCode == RESULT_CODE) {
			if (null == mUploadMessage){
				return;
			}
			Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
			mUploadMessage.onReceiveValue(result);
			mUploadMessage = null;
		}
	}

	@Override
	public void onClick(View v) {
    	switch (v.getId()) {
			case R.id.button_1:{
				User user = new User();
				Location location = new Location();
				location.address = "SDU";
				user.location = location;
				user.name = "大头鬼";

				webView.callHandler("functionInJs", new Gson().toJson(user), new CallBackFunction() {
					@Override
					public void onCallBack(String data) {
						Log.i(TAG, "button_1--functionInJs--" + data);
					}
				});
			}break;
			case R.id.button_2:{
				webView.callHandler("functionInJs", "data from Java", new CallBackFunction() {

					@Override
					public void onCallBack(String data) {
						// TODO Auto-generated method stub
						Log.i(TAG, "button_2--onCallBack " + data);
					}

				});
			}break;
			case R.id.button_3:{
				//webView.send("hello");
				webView.send("{a:hello}", new CallBackFunction() {
					@Override
					public void onCallBack(String data) {
						Log.i(TAG, "button_3 -- onCallBack = " + data);
					}
				});
			}break;
		}
	}


	private static final int PERMISSION_REQUEST_CODE = 102;
	private void permission(){
		List<String> permissionLists = new ArrayList<>();
		if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
			permissionLists.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
		}
		if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED){
			permissionLists.add(Manifest.permission.READ_PHONE_STATE);
		}

		if(!permissionLists.isEmpty()){//说明肯定有拒绝的权限
			ActivityCompat.requestPermissions(this, permissionLists.toArray(new String[permissionLists.size()]), PERMISSION_REQUEST_CODE);
		}else{
			//gotoMainAct();
		}
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		switch (requestCode) {
			case PERMISSION_REQUEST_CODE:
				if(grantResults.length > 0){
					for(int grantResult : grantResults){
						if(grantResult != PackageManager.PERMISSION_GRANTED){
							finish();
							return;
						}
					}
					//其他逻辑(这里当权限都同意的话就执行下一步逻辑)
					//gotoMainAct();
				}
				break;
			default:
				break;
		}
	}

}
